import { useEffect, useState, useRef } from "react";
import request from "../../axios";
import "./index.css";
import { useSelector } from "react-redux";
import { PullToRefreshify } from "react-pull-to-refreshify";
import { message } from "antd";

// 定义合同数据的类型
interface ContractData {
    name: string;
    code: string;
    contractTime: string;
}

interface htDataType {
    data?: ContractData[];
    totalPages?: number
}

const MyComponent = () => {
    const counter = useSelector((state: any) => state.counter.data);
    const [htData, setHtData] = useState<htDataType>({ data: []});
    const [refreshing, setRefreshing] = useState<boolean>(false);
    const [page, setPage] = useState(1);
    const [isLoading, setIsLoading] = useState(false);
    const scrollContainerRef = useRef<HTMLDivElement>(null);

    const getInitData = async () => {
        setIsLoading(true);
        try {
            const { data } = await request.get("/route/api/contracts", {
                accessToken: "",
                enterpriseId: counter?.corpId,
                keyword: "",
                type: "0",
                pageNum: page,
                pageSize: 10
            })

            if(data === undefined) {
                return;
            }

            if (page === 1) {
                setHtData(data);
            } else {
                // if(!data?.data?.length) {
                //     message.warning('暂无更多数据')
                // } else {
                //     message.warning('加载中...')
                // }
                setHtData(prevData => ({
                    data: [...(prevData.data || []), ...(data.data || [])]
                }));
            }
        } catch (error) {
            message.error('请求失败')
            console.error("获取数据时出错:", error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleRefresh = () => {
        setRefreshing(true);
        setPage(1);
        getInitData().then(() => {
            setRefreshing(false);
        });
    };

    let timer: any = null
    const handleScroll = (e:any) => {
        console.log(page,'page')
        let scrollTop = e.target.scrollTop
        let scrollHeight = e.target.scrollHeight
        let offsetHeight = Math.ceil(e.target.getBoundingClientRect().height)
        let currentHeight = scrollTop + offsetHeight
        if (currentHeight >= scrollHeight-1) {
            setPage(page + 1);
        }
    };

    const renderText = (pullStatus: any, percent: any) => {
        switch (pullStatus) {
            case "pulling":
                return (
                    <div>
                        下拉即可刷新{" "}
                        <span style={{ color: "green" }}>{`${percent.toFixed(0)}%`}</span>
                    </div>
                );
            case "canRelease":
                return "释放即可刷新...";
            case "refreshing":
                return "刷新中";
            case "complete":
                return "刷新成功";
            default:
                return "";
        }
    };

    useEffect(() => {
        getInitData();
    }, [page]);

    useEffect(() => {
        const container = scrollContainerRef.current;
        if (container) {
            container.addEventListener('scroll', handleScroll);
        }
        return () => {
            if (container) {
                container.removeEventListener('scroll', handleScroll);
            }
        };
    }, [isLoading]);

    return (
        <div className="container" ref={scrollContainerRef}>
            <PullToRefreshify
                refreshing={refreshing}
                onRefresh={handleRefresh}
                renderText={renderText}
            >
                <div className="scrollable-container">
                    {htData?.data?.map((item) => (
                        <div className="device-item" key={item.code}>
                            <div className="device-item-content">
                                <div className="device-item-title">{item.name}</div>
                                <span className="device-info">{item.code}</span>
                                <span className="device-address">
                                    合同时间：{item.contractTime}
                                </span>
                            </div>
                        </div>
                    ))}
                </div>
            </PullToRefreshify>
        </div>
    );
};

export default MyComponent;
    